﻿using AutoMapper;
using MediatR;
using RedDragon.Common.Domain.Process;
using RedDragon.Common.Infrastructure.Interface;
using RedDragon.ERP.ErroCodeEnum;
using T.Common.Domain.Common;

namespace RedDragon.ERP.API.Application.Commands.Proccess
{
    /// <summary>
    /// 添加工艺路线
    /// </summary>
    public class CreateProcessRouteHandler : IRequestHandler<CreateProcessRouteCommand, Result>
    {
        /// <summary>
        /// 工艺路线仓储
        /// </summary>
        private readonly IBaseRepository<ProcessRoutes> _processRouteRepository;

        /// <summary>
        /// 日志
        /// </summary>
        private readonly ILogger<CreateProcessRouteHandler> _logger;

        /// <summary>
        /// mapper类
        /// </summary>
        private readonly IMapper _mapper;

        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="processRouteRepository"></param>
        /// <param name="logger"></param>
        /// <param name="mapper"></param>
        public CreateProcessRouteHandler(IBaseRepository<ProcessRoutes> processRouteRepository,
                                         ILogger<CreateProcessRouteHandler> logger,
                                         IMapper mapper)
        {
            _processRouteRepository = processRouteRepository;
            _logger = logger;
            _mapper = mapper;
        }

        /// <summary>
        /// 添加工艺路线
        /// </summary>
        /// <param name="request"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public async Task<Result> Handle(CreateProcessRouteCommand request, CancellationToken cancellationToken)
        {
            var result = new Result() { Code = (int)CommonErrorCode.Added };
            try
            {
                //根据工艺编码与名称查垓编码与名称是否存在
                var process = await (await _processRouteRepository.GetAll()).Where(d => d.ProcessRouteName == request.ProcessRouteName || d.ProcessRouteNo == request.ProcessRouteNo).CountAsync();
                //判断如果存在提醒
                if (process > 0)
                {
                    result.Msg = "编码或名称已存在,请重新输入";
                }
                else
                {
                    //条件转换为类
                    var route = _mapper.Map<ProcessRoutes>(request);
                    //进行添加
                    var res = await _processRouteRepository.Add(route);
                    //判断是否添加成功
                    if (res > 0)
                    {
                        result.Code = (int)CommonErrorCode.Success;
                        result.Msg = "添加工艺路线成功";
                    }
                }
            }
            catch (Exception ex)
            {
                result.Msg = "添加工艺路线异常" + ex.Message;
                _logger.LogError("添加工艺路线异常" + ex.Message);
            }
            return result;
        }
    }
}
